package com.wsc.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wsc.entity.Statistics;
import com.wsc.repository.ConsumeLogRepository;
import com.wsc.repository.StatisticsRepository;
import com.wsc.service.StatisticsService;

@Service
@Transactional
public class StatisticsServiceImpl implements StatisticsService {
	@Autowired
	private StatisticsRepository ssr;
	@Autowired
	private ConsumeLogRepository cr;

	@Override
	public Map<String, Object> getAll(Map<String, Object> params) {
		Integer readroomid = (Integer) params.get("readroomid");
		Integer page = (Integer) params.get("page");
		Integer limit = (Integer) params.get("limit");
		List<Statistics> data = ssr.getAll(readroomid, page, limit);
		// count 数据总条数
		Integer count = ssr.getCount(readroomid);
		if (data.size() > 0) {
			params.put("code", 0);
			params.put("data", data);
			params.put("count", count);
		} else {
			params.put("code", 1);
			params.put("msg", "数据异常");
		}
		return params;
	}

	/***
	 * 获取chart数据
	 */
	@Override
	public List<Object[]> getChartData(String intime, String outtime) {
		return ssr.getChartData(intime, outtime);
	}

	@Override
	public void addFromConsumeLogToStatistics() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String today = sdf.format(new Date());
		// 获取今天consumelog各个阅览室使用数量
		List<Object[]> listToday = cr.getAllByTodayGroupByReadroomid(today);
		//年
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
		String year = sdf1.format(new Date());
		//月
		SimpleDateFormat sdf2 = new SimpleDateFormat("MM");
		String month = sdf2.format(new Date());
		//日
		SimpleDateFormat sdf3 = new SimpleDateFormat("dd");
		String day = sdf3.format(new Date());
		for (int i = 0; i < listToday.size(); i++) {
			Integer readroomid = (Integer) listToday.get(i)[0];
			// 原生sql count(*)查询结果类型为BigInteger
			Integer peoplenums = Integer.parseInt(listToday.get(i)[1].toString());
			Statistics s = new Statistics(null, readroomid, peoplenums, year, month, day);
			ssr.save(s);
		}

	}

}
